<?php

namespace app\middleware;

use InvalidArgumentException;
use think\Request, Exception;
use \app\common\library\Jwt as JwtLibrary;
use think\response\Html;
use think\response\Json;

class Jwt
{
    public function handle(Request $request, \Closure $next): Json|Html
    {
        $token = $request->header('Authorization');
        if (empty($token)) {
            return json(result()->fail(result()::LOGIN_EXPIRES));
        }
        try {
            JwtLibrary::instance()->authenticateJwtToken($token);
        } catch (InvalidArgumentException) {
            return json(result()->fail(result()::INVALID_TOKEN_PROVIDED));
        } catch (Exception $e) {
            return json(result()->setMsg($e->getMessage())->fail(result()::FAIL));
        }
        return $next($request);
    }
}